package com.table;

import com.appclient.ClientWizardController;
import com.appclient.DaoInstanceEnum;
import com.carpark.ejb.Model.EmployeesModel;
import com.wizardOther.Items.ValidationForm;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;

/**
 *
 * @author Vi
 */
public class EmployeeTableController extends ValidationForm{

    @FXML
    private TextField filterField;
    @FXML
    private TableView<EmployeesModel> empTable;
    @FXML
    private TableColumn<EmployeesModel, String> jobType;
    @FXML
    private TableColumn<EmployeesModel, String> name;
    @FXML
    private TableColumn<EmployeesModel, String> surname;
    @FXML
    private TableColumn<EmployeesModel, String> pesel;
    @FXML
    private TableColumn<EmployeesModel, String> city;
    @FXML
    private TableColumn<EmployeesModel, String> zipCode;
    @FXML
    private TableColumn<EmployeesModel, String> street;
    @FXML
    private TableColumn<EmployeesModel, String> house;
    @FXML
    private TableColumn<EmployeesModel, String> local;
    @FXML
    private TableColumn<EmployeesModel, String> start;
    @FXML
    private TableColumn<EmployeesModel, String> end;
    @FXML
    private TableColumn<EmployeesModel, String> phone;
    @FXML
    private TableColumn<EmployeesModel, String> salary;
    @FXML
    private TableColumn<EmployeesModel, String> email;
    @FXML
    private TableColumn<EmployeesModel, String> password;
    @FXML
    private TableColumn<EmployeesModel, String> comment;
    
    
    @FXML
    private Button choose;
    private ObservableList<EmployeesModel> masterData = FXCollections.observableArrayList();
    private ObservableList<EmployeesModel> filteredData = FXCollections.observableArrayList();
    private Stage dialogStage;
    private ClientWizardController wizard;
    private Integer selectedEmp;

    public Integer getSelectedEmp() {
        return selectedEmp;
    }

    
    
    

    public EmployeeTableController() {
        List<EmployeesModel> data = DaoInstanceEnum.INSTANCE.getDao().getAllEmployees();
        for (EmployeesModel emp : data) {
          emp.setJobType(renameJobTypeToPolish(emp.getJobType()));
          emp.setReleaseDate(Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(emp.getReleaseDate())));
          emp.setEmploymentDate(Date.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(emp.getEmploymentDate())));
            masterData.add(emp);
        }

        filteredData.addAll(masterData);
        masterData.addListener(new ListChangeListener<EmployeesModel>() {
            @Override
            public void onChanged(ListChangeListener.Change<? extends EmployeesModel> change) {
                updateFilteredData();
            }
        });
    }

    /**
     * Initializes the controller class. This method is automatically called
     * after the fxml file has been loaded.
     */
    @FXML
    private void initialize() {
        jobType.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("jobType"));
        name.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("surname"));
        surname.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("firstname"));
        pesel.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("peselNumber"));
        city.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("city"));
        zipCode.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("zipCode"));
        street.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("street"));
        house.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("houseNumber"));
        local.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("localNumber"));
        start.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("employmentDate"));
        end.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("releaseDate"));
        phone.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("phone"));
        salary.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("salary"));
        email.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("email"));
        password.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("password"));
        comment.setCellValueFactory(
                new PropertyValueFactory<EmployeesModel, String>("comments"));
       
        empTable.setItems(filteredData);

        filterField.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable,
                    String oldValue, String newValue) {
                updateFilteredData();
            }
        });
    }

    /**
     * Updates the filteredData to contain all data from the masterData that
     * matches the current filter.
     */
    private void updateFilteredData() {
        filteredData.clear();

        for (EmployeesModel p : masterData) {
            if (matchesFilter(p)) {
                filteredData.add(p);
            }
        }

        // Must re-sort table after items changed
        reapplyTableSortOrder();
    }

    /**
     * Returns true if the person matches the current filter. Lower/Upper case
     * is ignored.
     *
     * @param car
     * @return
     */
    private boolean matchesFilter(EmployeesModel emp) {
        String filterString = filterField.getText();
        if (filterString == null || filterString.isEmpty()) {
            return true;
        }
        String lowerCaseFilterString = filterString.toLowerCase();

        if (emp.getJobType().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (emp.getSurname().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (emp.getFirstname().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (emp.getPeselNumber().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
        if (emp.getCity().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
         if (emp.getZipCode().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
          if (emp.getStreet().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
          if (emp.getHouseNumber().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
           if ((emp.getLocalNumber().toString()).toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
            if ((emp.getEmploymentDate().toString()).toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
             if ((emp.getReleaseDate().toString()).toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
              if (emp.getPhone().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
          if (String.valueOf(emp.getSalary()).toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
           if (emp.getEmail().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
            if (emp.getPassword().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
             if (emp.getComments().toLowerCase().indexOf(lowerCaseFilterString) != -1) {
            return true;
        }
         
        return false;
    }

    public void setDialogStage(Stage dialogStage) {
        this.dialogStage = dialogStage;
    }

    private void reapplyTableSortOrder() {
        ArrayList<TableColumn<EmployeesModel, ?>> sortOrder = new ArrayList<>(empTable.getSortOrder());
        empTable.getSortOrder().clear();
        empTable.getSortOrder().addAll(sortOrder);
    }

    @FXML
    private void makeChoice(ActionEvent event) {
        if (event.getSource() == choose) {
            try{
                 selectedEmp = empTable.getSelectionModel().getSelectedItem().getEmployeeId();
            }
            catch(Exception e){
                 createPopup("Zaznacz najpierw w tabeli pojazd!");
            }
            if (selectedEmp != null) {
                dialogStage.close();
            }
        }
    }

    public void setWizard(ClientWizardController wizard) {
        this.wizard = wizard;
    }
}
